package org.thomias.exo6.swtmultithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

public class Application extends ApplicationWindow {
	Table table;
	TableEditor[] editors;
	private ExecutorService pool;

	public Application() {
		super(null);
		addToolBar(SWT.FLAT | SWT.WRAP);
		addMenuBar();
		addStatusLine();
	}

	@Override
	protected Control createContents(Composite parent) {

		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		composite.setLayout(gl_composite);

		table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		TableColumn tblclmnName = new TableColumn(table, SWT.NONE);
		tblclmnName.setWidth(57);
		tblclmnName.setText("Name");

		TableColumn tblclmnSize = new TableColumn(table, SWT.NONE);
		tblclmnSize.setWidth(33);
		tblclmnSize.setText("Size");

		TableColumn tblclmnUd = new TableColumn(table, SWT.NONE);
		tblclmnUd.setWidth(33);
		tblclmnUd.setText("U/D");

		TableColumn tblclmnProgress = new TableColumn(table, SWT.NONE);
		tblclmnProgress.setWidth(92);
		tblclmnProgress.setText("Progress");

		TableColumn tblclmnSpeed = new TableColumn(table, SWT.NONE);
		tblclmnSpeed.setWidth(50);
		tblclmnSpeed.setText("Speed");

		TableColumn tblclmnElapsed = new TableColumn(table, SWT.NONE);
		tblclmnElapsed.setWidth(58);
		tblclmnElapsed.setText("Elapsed");

		TableColumn tblclmnEstimated = new TableColumn(table, SWT.NONE);
		tblclmnEstimated.setWidth(65);
		tblclmnEstimated.setText("Estimated");
		editors = new TableEditor[10];
		for (int i = 0; i < 10; i++) {
			pool.execute(new BarUpdater(this, i));
		}

		return composite;
	}

	public static void main(String args[]) {
		try {
			Application window = new Application();
			window.pool = Executors.newFixedThreadPool(4);
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
			window.pool.shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("Multithread bars");
	}

	public void refresh() {
		for (TableEditor te : editors) {
			if (te != null) {
				te.layout();
			}
		}
	}
}
